﻿using Jint.Native;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Expression.Entity;
using T.FAS.Runtime.MF.Activities.Helper;
using T.FAS.Runtime.MF.Dao;
using T.FAS.Runtime.MF.SPI;
using  T.ServiceFramework.ServiceGateway.Client;
using  T.ServiceFramework.ServiceGateway.ClientExtension;
using YamlDotNet.Core.Tokens;

namespace T.FAS.Runtime.MF.Activities
{
    public class FasExpDebugService : IFasExpService
    {
        public ExprResult DQExecute(string jsString, Dictionary<string, object> inputParam)
        {
            // return ExprService.GetInstance.DQExecute(jsString, inputParam);
            throw new NotImplementedException();
        }

        public ExprResult Execute(string jsString, FASContext fASContext, Dictionary<string, object> inputParam)
        {
            // return ExprService.GetInstance.Execute(jsString, fASContext, inputParam);

            var dicParams = new Dictionary<string, string>();
            foreach (var key in inputParam.Keys)
            {
                dicParams.Add(key, Newtonsoft.Json.JsonConvert.SerializeObject(inputParam[key]));
            }
            return new SGHttpClient(true).PostCurrentIDC<ExprResult>("FASR-JSExecute", dicParams, 20).data;
        }

        public ExprResult JSExecute(string jsString, Dictionary<string, object> inputParam)
        {
            // return ExprService.GetInstance.JSExecute(jsString, inputParam);
            throw new NotImplementedException();
        }

        public ExprResult Debug(string jsString, Dictionary<string, object> inputParam, Dictionary<string, string> extraParams)
        {
            var envUrl = string.Empty;
            var appId = string.Empty;
            if (extraParams.ContainsKey("DebugEnvUrl"))
            {
                envUrl = extraParams["DebugEnvUrl"];
            }
            if (extraParams.ContainsKey("AppID"))
            {
                appId = extraParams["AppID"];
            }
            var result = ExprDebug(jsString, inputParam, envUrl, appId);

            return result;
        }

        public ExprResult JSExecuteNotReport(string jsString, Dictionary<string, object> inputParam)
        {
            //  return ExprService.GetInstance.JSExecuteNotReport(jsString, inputParam);
            throw new NotImplementedException();
        }

        private ExprResult ExprDebug(string jsString, Dictionary<string, object> inputParam,string envUrl,string appId)
        {
            var result = new ExprResult();
            var sid = "FASR-ExprDebugInternal";

            var dicParams = new Dictionary<string, string>();
            dicParams.Add("expr", jsString);
            dicParams.Add("inputParam", Newtonsoft.Json.JsonConvert.SerializeObject(inputParam));
            try
            {
                LogUtil.Log($"jsString={JsonConvert.SerializeObject(jsString)}");
                // var url = "http://sgi.t8.xyz:7778/api/Invoke?SID={0}"; 
                var url = $"{envUrl}/api/Invoke?SID={sid}&fasdevappid={appId}";

                var responseText = HttpHelper.PostUrl(url, "", JsonConvert.SerializeObject(dicParams));


                if (!string.IsNullOrEmpty(responseText))
                {
                    var jToken = JToken.Parse(responseText);
                    var data = jToken.SelectToken("$.data")?.ToString();
                    var executResult = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
                    LogUtil.Log($"executResult={JsonConvert.SerializeObject(executResult)}");
                    object state, resultObj, errMsg;
                    ResultState enumState;
                    if (executResult.TryGetValue("State", out state) && Enum.TryParse<ResultState>(state.ToString(), out enumState))
                    {
                        result.State = enumState;
                    }
                    if (executResult.TryGetValue("Result", out resultObj))
                    {
                        result.Result = resultObj;
                    }
                    if (executResult.TryGetValue("ErrMsg", out errMsg))
                    {
                        result.ErrMsg = errMsg.ToString();
                    }
                }
                else
                {
                    LogUtil.Log($"Debug={responseText}");
                    result.State = ResultState.Fail;
                }

            }
            catch (Exception ex)
            {
                LogUtil.Log($"Debug={ex.ToString()}");
                result.State = ResultState.Fail;
                result.ErrMsg = ex.Message;
            }
            return result;
        }
    }
}
